import { defineStore } from 'pinia'
import type { Post, Category, Comment, PostPagination } from '@/types/forum'
import { getPosts, getPostDetail, createPost, updatePost, deletePost, getCategories, createComment, deleteComment, likePost } from '@/api/forum'

interface ForumState {
  posts: Post[]
  post: Post | null
  categories: Category[]
  comments: Comment[]
  pagination: PostPagination
  isLoading: boolean
  error: string | null
}

export const useForumStore = defineStore('forum', {
  state: (): ForumState => ({
    posts: [],
    post: null,
    categories: [],
    comments: [],
    pagination: {
      currentPage: 1,
      total: 0,
      pageSize: 10,
      items: []
    },
    isLoading: false,
    error: null
  }),
  
  getters: {
    // 根据分类获取帖子
    postsByCategory: (state) => (categoryId: number) => {
      if (!categoryId) return state.posts
      return state.posts.filter(post => post.categoryId === categoryId)
    }
  },
  
  actions: {
    // 获取帖子列表
    async fetchPosts(params?: { categoryId?: number; keyword?: string; page?: number; pageSize?: number }) {
      try {
        this.isLoading = true
        this.error = null
        const response = await getPosts(params || {})
        this.posts = response.items
        this.pagination = {
          currentPage: response.currentPage,
          total: response.total,
          pageSize: response.pageSize,
          items: response.items
        }
        return response
      } catch (error: any) {
        this.error = error.message || '获取帖子列表失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取单个帖子详情
    async fetchPostById(id: number) {
      try {
        this.isLoading = true
        this.error = null
        const response = await getPostDetail(id)
        this.post = response
        this.comments = response.comments || []
        return response
      } catch (error: any) {
        this.error = error.message || '获取帖子详情失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 创建帖子
    async createPost(postData: Omit<Post, 'id' | 'createdAt' | 'updatedAt' | 'userId' | 'username' | 'avatar'>) {
      try {
        this.isLoading = true
        this.error = null
        const response = await createPost(postData)
        // 刷新帖子列表
        await this.fetchPosts({ page: this.pagination.currentPage, pageSize: this.pagination.pageSize })
        return response
      } catch (error: any) {
        this.error = error.message || '创建帖子失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 更新帖子
    async updatePost(id: number, postData: Partial<Post>) {
      try {
        this.isLoading = true
        this.error = null
        const response = await updatePost(id, postData)
        // 更新当前帖子详情
        if (this.post && this.post.id === id) {
          this.post = { ...this.post, ...response }
        }
        // 刷新帖子列表
        await this.fetchPosts({ page: this.pagination.currentPage, pageSize: this.pagination.pageSize })
        return response
      } catch (error: any) {
        this.error = error.message || '更新帖子失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 删除帖子
    async deletePost(id: number) {
      try {
        this.isLoading = true
        this.error = null
        const response = await deletePost(id)
        // 从列表中移除帖子
        this.posts = this.posts.filter(post => post.id !== id)
        // 如果删除的是当前查看的帖子，清除帖子详情
        if (this.post && this.post.id === id) {
          this.post = null
          this.comments = []
        }
        // 更新分页信息
        this.pagination.total -= 1
        return response
      } catch (error: any) {
        this.error = error.message || '删除帖子失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取分类列表
    async fetchCategories() {
      try {
        this.isLoading = true
        const response = await getCategories()
        this.categories = response
        return response
      } catch (error: any) {
        console.error('获取分类列表失败:', error)
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 创建评论
    async createComment(commentData: Omit<Comment, 'id' | 'createdAt' | 'updatedAt' | 'userId' | 'username' | 'avatar'>) {
      try {
        this.isLoading = true
        this.error = null
        const response = await createComment(commentData)
        // 添加到评论列表
        this.comments.push(response)
        // 更新帖子的评论数
        if (this.post) {
          this.post.commentCount = (this.post.commentCount || 0) + 1
        }
        return response
      } catch (error: any) {
        this.error = error.message || '发表评论失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 删除评论
    async deleteComment(commentId: number) {
      try {
        this.isLoading = true
        const response = await deleteComment(commentId)
        // 从评论列表中移除
        this.comments = this.comments.filter(comment => comment.id !== commentId)
        // 更新帖子的评论数
        if (this.post) {
          this.post.commentCount = Math.max(0, (this.post.commentCount || 0) - 1)
        }
        return response
      } catch (error: any) {
        console.error('删除评论失败:', error)
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 点赞帖子
    async likePost(postId: number) {
      try {
        const response = await likePost(postId)
        // 更新帖子的点赞数
        const post = this.posts.find(p => p.id === postId)
        if (post) {
          post.likeCount = (post.likeCount || 0) + 1
          post.isLiked = true
        }
        if (this.post && this.post.id === postId) {
          this.post.likeCount = (this.post.likeCount || 0) + 1
          this.post.isLiked = true
        }
        return response
      } catch (error: any) {
        console.error('点赞失败:', error)
        throw error
      }
    },
    
    // 清除错误
    clearError() {
      this.error = null
    },
    
    // 清除帖子详情
    clearPostDetail() {
      this.post = null
      this.comments = []
    }
  }
})